<!-- Created by henian.xu on 2018/11/9. -->

<template>
    <Page class="container">
        <Panel label="分销商入驻">
            <div
                class="row"
                style="margin-top: 50px;margin-bottom: 50px;">
                <div class="col-3">&nbsp;</div>
                <div class="col-18">
                    <StepProgressBar
                        v-model="currentStep"
                        :data="['账号信息','企业信息','等待审核结果']"/>
                </div>
                <div class="col-3">&nbsp;</div>
            </div>
            <div class="row">
                <div class="col-5">&nbsp;</div>
                <div class="col-14">
                    <XForm
                        ref="form1"
                        v-show="currentStep===1"
                        horizontal
                        label-align="right"
                        label-width="7em"
                        :models="formModel"
                        :rules="formRules"
                    >
                        <FormItem
                            ref="accountEmail"
                            label="账号邮箱: "
                            prop="accountEmail">
                            <XInput
                                v-model="formModel.accountEmail"
                                :disabled="isEdit"/>
                        </FormItem>
                        <FormItem
                            v-if="!isEdit"
                            label="邮箱验证码: "
                            prop="emailVerificationCode">
                            <XInput v-model="formModel.emailVerificationCode"/>
                            <div
                                v-if="emailCountDown"
                                class="append btn"
                                slot="append">获取验证码{{ emailCountDown }}</div>
                            <div
                                v-else
                                class="append btn"
                                slot="append"
                                @click="onEmailCheck">获取验证码</div>
                        </FormItem>
                        <FormItem
                            ref="accountMobile"
                            label="联系手机: "
                            prop="accountMobile">
                            <XInput
                                v-model="formModel.accountMobile"
                                :disabled="isEdit"/>
                        </FormItem>
                        <FormItem
                            v-if="!isEdit"
                            ref="jCaptcha"
                            label="图片验证码: "
                            prop="jCaptcha">
                            <XInput v-model="formModel.jCaptcha"/>
                            <div
                                class="append captcha"
                                :style="`background-image: url('${captchaSrc}');width: 200px;`"
                                slot="append"
                                @click="onAuthCodeChange"><div style="width: 100px;"/></div>
                        </FormItem>
                        <FormItem
                            v-if="!isEdit"
                            label="短信验证码: "
                            prop="mobileVerificationCode">
                            <XInput v-model="formModel.mobileVerificationCode"/>
                            <div
                                v-if="countDown"
                                class="append btn"
                                slot="append">获取验证码{{ countDown }}</div>
                            <div
                                v-else
                                class="append btn"
                                slot="append"
                                @click="onMobileCheck">获取验证码</div>
                        </FormItem>
                        <FormItem
                            label="联系人姓名: "
                            prop="accountRealName">
                            <XInput v-model="formModel.accountRealName"/>
                        </FormItem>
                        <FormItem label="账号类型选择">
                            <Checkbox
                                type="radio"
                                v-model="formModel.authType"
                                :val="1">企业</Checkbox>
                            <Checkbox
                                type="radio"
                                v-model="formModel.authType"
                                :val="2">个体工商户</Checkbox>
                        </FormItem>
                        <FormItem label="">
                            <Checkbox v-model="formModel.agree">
                                <span class="fs-small tc-g6">
                                    创建平台账号的同时，我同意遵守
                                    <a
                                        href="javascript:;"
                                        class="tc-main">《搜货网服务条款》</a>
                                    及
                                    <a
                                        href="javascript:;"
                                        class="tc-main">《隐私声明》</a>
                                </span>
                            </Checkbox>
                        </FormItem>
                        <!--<FormItem label="长文本: ">
                            <XInput type="textarea"/>
                            <div
                                class="append btn"
                                slot="append">获取验证码</div>
                        </FormItem>
                        <FormItem label="账号邮箱: ">
                            <select class="select2">
                                <option value="">请选择</option>
                                <option value="1">选择1</option>
                                <option value="2">选择2</option>
                                <option value="3">选择3</option>
                            </select>
                        </FormItem>
                        <FormItem label="账号邮箱: ">
                            <input type="text">
                        </FormItem>-->
                    </XForm>
                    <XForm
                        ref="form2"
                        v-show="currentStep===2"
                        horizontal
                        label-align="right"
                        label-width="10em"
                        :models="formModel"
                        :rules="formRules"
                    >
                        <FormItem
                            label="企业名称: "
                            prop="companyName">
                            <XInput v-model="formModel.companyName"/>
                        </FormItem>
                        <FormItem
                            label="法人名称: "
                            prop="legalRealName">
                            <XInput v-model="formModel.legalRealName"/>
                        </FormItem>
                        <FormItem
                            label="法人身份证号: "
                            prop="legalIdCardNo">
                            <XInput v-model="formModel.legalIdCardNo"/>
                        </FormItem>
                        <FormItem
                            :label="`所在地: ${region}`"
                            prop="companyRegionId">
                            <RegionPicker v-model="formModel.companyRegionId"/>
                        </FormItem>
                        <FormItem
                            label="详细地址: "
                            prop="companyAddress">
                            <XInput v-model="formModel.companyAddress"/>
                        </FormItem>
                        <FormItem
                            label="营业执照照片: "
                            prop="cuscImages">
                            <Upload
                                v-model="formModel.cuscImages"
                                action="/rpc/comm/rs/attachment/uploadBuyerAuthInfoImage"
                                :column="4"
                                :max-files="1"/>
                            <div class="fs-small tc-g6">图片小于5M，格式jpg、png、gif</div>
                        </FormItem>
                        <FormItem
                            label="统一社会信用代码: "
                            prop="cuscCode">
                            <XInput v-model="formModel.cuscCode"/>
                        </FormItem>
                        <FormItem
                            v-if="formModel.authType===1"
                            label="截止有效期: "
                            prop="cuscExpire">
                            <DatePicker v-model="formModel.cuscExpire"/>
                        </FormItem>
                    </XForm>
                    <div
                        class="ta-c ma-t ma-b"
                        v-if="currentStep===3">
                        <div class="tc-main">进度查询码:<span style="font-size: 30px;font-weight: bold;">12345679</span></div>
                        <div style="font-size: 18px; font-weight: bold;">
                            您的入驻申请已提交，我们将在1-3个工作日内进行审核。<br>
                            您可以通过查询码查询审核进度，审核结果将会以邮件和手机短信通知您！
                        </div>
                    </div>
                </div>
                <div class="col-5">&nbsp;</div>
            </div>
            <div class="ta-c">
                <template v-if="currentStep<3">
                    <div
                        :class="['btn','btn-big',formModel.agree?'btn-main':'btn-disabled']"
                        @click="onStep">{{ currentStep===1?'下一步':'上一步' }}</div>
                    <div
                        class="btn btn-big btn-main"
                        v-if="currentStep===2"
                        @click="onSubmit">提&nbsp;&nbsp;交</div>
                </template>
                <template v-else>
                    <linker
                        to="/"
                        ssr
                        class="btn btn-big btn-main">返回首页</linker>
                    <div class="btn btn-big btn-main">查询进度</div>
                </template>
            </div>
        </Panel>
    </Page>
</template>

<script>
import PageMixin from '~/mixins/page.js';
export default {
    mixins: [PageMixin],
    /*asyncData({ app }) {
        return app.$axios.get('/rpc/comm/rs/region/getChild').then(json => {
            const result = json.data.data;
            return { result };
        });
    },*/
    data() {
        return {
            currentStep: 1,
            radio: 1,
            region: 0,
            /*formModel: {
                id: '', //申请ID
                accountEmail: 'asdf@asdf.asdf', //账号邮箱
                emailVerificationCode: '123456', //邮箱验证码
                accountMobile: '18060082532', //手机号
                mobileVerificationCode: '123456', //手机验证码
                jCaptcha: 'asdf', // 图片验证码
                accountRealName: 'xhn', //联系人姓名
                authType: 1,
                agree: true, //同意
                companyName: '企业名称', //企业名称
                legalRealName: '法人姓名', //法人姓名
                legalIdCardNo: '法人身份证号', //法人身份证号
                companyRegionId: 0, //所在地区ID
                companyAddress: '详细地址', //详细地址
                cuscImage: '营业执照', //营业执照
                cuscImages: [],
                cuscCode: '统一社会信用代码', //统一社会信用代码
                cuscExpire: 1541894400000, //截止有效期
            },*/
            formModel: {
                id: '', //申请ID
                accountEmail: '', //账号邮箱
                emailVerificationCode: '', //邮箱验证码
                accountMobile: '', //手机号
                mobileVerificationCode: '', //手机验证码
                jCaptcha: '', // 图片验证码
                accountRealName: '', //联系人姓名
                authType: 1,
                agree: false, //同意
                companyName: '', //企业名称
                legalRealName: '', //法人姓名
                legalIdCardNo: '', //法人身份证号
                companyRegionId: 0, //所在地区ID
                companyAddress: '', //详细地址
                cuscImage: '', //营业执照
                cuscImages: [],
                cuscCode: '', //统一社会信用代码
                cuscExpire: 0, //截止有效期
            },
            formRules: {
                accountEmail: [
                    {
                        required: true,
                        message: '邮箱号不能为空',
                    },
                    {
                        validator: this.$utils.Valid.email,
                        message: '邮箱格式不正确',
                    },
                    {
                        validator: this.checkEmail,
                        // 远程验证 message 远程返回
                    },
                ],
                accountMobile: [
                    {
                        required: true,
                        message: '手机号不能为空',
                    },
                    {
                        validator: this.$utils.Valid.mobile,
                        message: '手机格式不正确',
                    },
                    {
                        validator: this.checkMobile,
                        // 远程验证 message 远程返回
                    },
                ],
                jCaptcha: {
                    required: true,
                    message: '手机号不能为空',
                },
                emailVerificationCode: {
                    required: true,
                    message: '不能为空',
                }, //邮箱验证码
                mobileVerificationCode: {
                    required: true,
                    message: '不能为空',
                }, //手机验证码
                accountRealName: {
                    required: true,
                    message: '不能为空',
                }, //联系人姓名
                // agree: '', //同意
                companyName: {
                    required: true,
                    message: '不能为空',
                }, //企业名称
                legalRealName: {
                    required: true,
                    message: '不能为空',
                }, //法人姓名
                legalIdCardNo: {
                    required: true,
                    message: '不能为空',
                }, //法人身份证号
                companyRegionId: {
                    required: true,
                    message: '不能为空',
                }, //所在地区ID
                companyAddress: {
                    required: true,
                    message: '不能为空',
                }, //详细地址
                cuscImages: {
                    type: 'array',
                    required: true,
                    message: '不能为空',
                }, //营业执照
                cuscCode: {
                    required: true,
                    message: '不能为空',
                }, //统一社会信用代码
                cuscExpire: {
                    required: true,
                    message: '不能为空',
                }, //截止有效期
            },
            countDown: 0,
            countDownTimer: 0,
            emailCountDown: 0,
            emailCountDownTimer: 0,
            captchaSrc: `/rpc/comm/rs/captcha/get-captcha`,
            isEdit: false,
        };
    },
    head() {
        return {
            title: '分销商入驻',
        };
    },
    computed: {
        queryCode() {
            return this.$route.query.queryCode || '';
        },
        account() {
            return this.$route.query.account || '';
        },
        hasEdit() {
            return !!this.queryCode && !!this.account;
        },
    },
    methods: {
        onMobileCheck() {
            this.$refs['form1'].clearValidate();
            Promise.all([this.$refs['accountMobile'].validate(), this.$refs['jCaptcha'].validate()]).then(() => {
                this.$axios
                    .post('/rpc/comm/rs/sms/sendVerificationCode', {
                        sendMobile: this.formModel.accountMobile,
                        jCaptcha: this.formModel.jCaptcha,
                    })
                    .then(() => {
                        this.startCountDown(60);
                    });
            });
        },
        onEmailCheck() {
            this.$refs['form1'].clearValidate();
            this.$refs['accountEmail'].validate().then(() => {
                this.$axios
                    .post('/rpc/comm/rs/email/sendVerificationCode', {
                        sendEmail: this.formModel.accountEmail,
                    })
                    .then(() => {
                        this.startEmailCountDown(60);
                    });
            });
        },
        async checkEmail(rule, value, callback) {
            // callback(new Error('res.msg'));
            if (this.isEdit) callback(); // 编辑时不验证
            let res = false;
            await this.$axios
                .get('/rpc/buyer/mb/buyerAuthInfo/checkEmail', {
                    account: this.formModel.accountEmail,
                    _isHandleError: true,
                })
                .then(json => {
                    res = json.data;
                    // console.log(res);
                });
            // console.log(123);
            if (!res.success) {
                callback(new Error(res.msg));
            } else {
                callback();
            }
        },
        async checkMobile(rule, value, callback) {
            // callback(new Error('res.msg'));
            if (this.isEdit) callback(); // 编辑时不验证
            let res = false;
            await this.$axios
                .get('/rpc/buyer/mb/buyerAuthInfo/checkMobile', {
                    account: this.formModel.accountMobile,
                    _isHandleError: true,
                })
                .then(json => {
                    res = json.data;
                    // console.log(res);
                });
            // console.log(123);
            if (!res.success) {
                callback(new Error(res.msg));
            } else {
                callback();
            }
        },
        startCountDown(val) {
            this.countDown = val;
            clearInterval(this.countDownTimer);
            this.countDownTimer = setInterval(() => {
                this.countDown--;
                if (this.countDown <= 0) {
                    this.onAuthCodeChange();
                    clearInterval(this.countDownTimer);
                    this.countDownTimer = 0;
                }
            }, 1000);
        },
        startEmailCountDown(val) {
            this.emailCountDown = val;
            clearInterval(this.emailCountDownTimer);
            this.emailCountDownTimer = setInterval(() => {
                this.emailCountDown--;
                if (this.emailCountDown <= 0) {
                    this.onAuthCodeChange();
                    clearInterval(this.emailCountDownTimer);
                    this.emailCountDownTimer = 0;
                }
            }, 1000);
        },

        onAuthCodeChange() {
            this.captchaSrc = `/rpc/comm/rs/captcha/get-captcha?_T=${Date.now()}`;
        },
        onStep() {
            if (!this.formModel.agree) return;
            if (this.currentStep === 1) {
                this.onNext().then(() => {
                    this.currentStep++;
                });
            } else {
                this.currentStep--;
            }
        },
        onNext() {
            return this.$refs['form1'].validate();
        },
        onSubmit() {
            this.$refs['form2'].validate().then(() => {
                const data = { ...this.formModel };
                data.cuscImage = this.formModel.cuscImages
                    .reduce((prev, next) => (prev.push(next.name), prev), [])
                    .join(',');
                delete data.cuscImages;
                this.$axios.post('/rpc/buyer/mb/buyerAuthInfo/saveBuyerAuthInfo', data).then(json => {
                    console.log(data.cuscImage);
                    const res = json.data.data;
                    this.currentStep = 3;
                    this.$router.push(
                        `/register/result?queryCode=${res.queryCode}&accountEmail=${res.accountEmail}&accountMobile=${
                            res.accountMobile
                        }`,
                    );
                    console.log('form2');
                });
            });
        },
        // -------------编辑-------------------------
        recoverFormModel(data) {
            Object.keys(this.formModel).forEach(key => {
                // if (key === 'goodsSpecList') return;
                // if (key === 'goodsImage') return;
                // if (key === 'goodsDetailImage') return;
                // if (key === 'skuSpecList') return;
                let val = data[key];
                if (key === 'cuscExpire') {
                    val = +this.$moment(val).format('x');
                } else if (key === 'cuscImage') {
                    this.formModel['cuscImages'] = val.split(',').reduce((p, c) => {
                        p.push({
                            name: c,
                            address: `${data.baseUrl}${c}`,
                        });
                        return p;
                    }, []);
                    return;
                }
                this.formModel[key] = val === undefined || val === null ? this.formModel[key] : val;
            });
            this.isEdit = true;
        },
        getAuthInfoDetail() {
            if (!this.hasEdit) return;

            this.$axios
                .get('/rpc/buyer/mb/buyerAuthInfo/getAuthInfoDetail', {
                    queryCode: this.queryCode,
                    account: this.account,
                })
                .then(json => {
                    const result = json.data.data;
                    console.log(result.authInfo);
                    this.recoverFormModel(result.authInfo);
                });
        },
    },
    mounted() {
        this.getAuthInfoDetail();
    },
};
</script>

<style lang="scss">
.captcha {
    background-size: 100% 100%;
}
</style>
